import json

from PyQt6 import uic
from PyQt6.QtCore import Qt, QSize
from PyQt6.QtGui import QIcon, QPixmap, QImageReader
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QGridLayout, QHBoxLayout, QListWidgetItem, QSizePolicy, \
    QSplitter, QToolButton, QMessageBox

from utils.index import resource_path
from front.components.historyListDel import Window as HistoryListDel
from utils.showImage import load_hd_pixmap


class Window(QWidget):
    def __init__(self, path, inclined_shaft):
        super().__init__()
        self.image_label = None  # 展示出图结果的标签控件
        self.path = path  # 存放历史记录文件的路径
        self.data = None  # 读取到的桥图|斜井历史记录
        self.inclined_shaft = inclined_shaft  # 桥图|斜井页面的对象
        self.module_name = "桥图|斜井"
        self.e_name = "inclinedShaft"
        self.ui = uic.loadUi(resource_path("static/ui/historyInclinedShaft.ui"), self)  # 加载 UI 文件
        self.init_style()  # 初始化页面样式，页面内容
        self.init_event()

    # ========================================================
    # 重写方法
    # ========================================================
    # 根据窗口宽度动态调整
    def resizeEvent(self, event):
        # 获取窗口当前宽度
        width = self.width()
        # 根据窗口宽度动态调整字体大小
        fontSize = int(width / 150)
        if fontSize < 10:
            fontSize = 10
        if fontSize > 18:
            fontSize = 18

        # 定义一个递归函数来遍历所有子控件，并设置字体大小
        def traverse_widgets(widget):
            if hasattr(widget, 'setFont'):
                font = widget.font()
                font.setPointSize(fontSize)
                widget.setFont(font)
            for child in widget.children():
                traverse_widgets(child)

        # 从主窗口开始遍历所有控件
        traverse_widgets(self)

        # 显示的图片
        image_width = int(width / 3 * 2)
        image_height = int(image_width / 4 * 3)
        if image_width < 800:
            image_width = 800
        if image_height < 600:
            image_height = 600
        self.ui.widget.setFixedSize(image_width, image_height)

        # 设置ToolButton的大小
        buttons = self.findChildren(QToolButton)
        for btn in buttons:
            icon_size = int(width / 100)
            btn.setIconSize(QSize(icon_size, icon_size))

        super().resizeEvent(event)

    # 重写 keyPressEvent 方法，按下左右按键可以控制listWeight选项，左箭头选项上移，右箭头选项下移
    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_Left:
            count = len(self.data)
            index = self.ui.listWidget.currentRow()
            index = index - 1
            if index < 0:
                index = count - 1
            self.init_detail(self.data[index], index + 1)
            self.ui.listWidget.setCurrentRow(index)
        elif event.key() == Qt.Key.Key_Right:
            count = len(self.data)
            index = self.ui.listWidget.currentRow()
            index = index + 1
            if index >= count:
                index = 0
            self.init_detail(self.data[index], index + 1)
            self.ui.listWidget.setCurrentRow(index)
        super().keyPressEvent(event)  # 调用父类的 keyPressEvent 处理其他按键

    # ========================================================
    # 初始化页面
    # ========================================================

    def init_style(self):
        self.ui.setWindowTitle(f"SeismicPlot-{self.module_name}历史记录")
        self.ui.setWindowIcon(QIcon(resource_path('static/image/favicon.ico')))
        self.ui.scrollArea.setStyleSheet("background-color: white;")

        # 设置布局
        line = self.ui.line
        line.setParent(None)
        # 创建 QSplitter
        splitter = QSplitter()
        # 获取 listWidget 和 scrollArea
        list_widget = self.ui.listWidget
        scroll_area = self.ui.scrollArea
        # 将 listWidget 和 scrollArea 添加到 QSplitter 中
        splitter.addWidget(list_widget)
        splitter.addWidget(scroll_area)
        sizes = [300, 900]
        splitter.setSizes(sizes)
        # 将 QSplitter 添加到主布局
        grid_layout = QGridLayout()
        grid_layout.addWidget(splitter, 0, 0)
        self.setLayout(grid_layout)

        # 设置图标
        self.ui.toolButton.setIcon(QIcon(resource_path('static/image/load.png')))  # 导入
        self.ui.toolButton_2.setIcon(QIcon(resource_path('static/image/del.png')))  # 删除
        self.ui.toolButton_3.setIcon(QIcon(resource_path('static/image/dels.png')))  # 批量删除

        self.init_content()

    # 初始化页面的内容
    def init_content(self):
        list_widget = self.ui.listWidget
        list_widget.clear()  # 删除 QListWidget 中的所有选项

        with open(self.path, 'r', encoding='utf-8') as file:
            history_data = json.load(file)
            inclined_shaft_history_data = history_data.get(self.e_name, [])
            if len(inclined_shaft_history_data) == 0:
                QMessageBox.critical(None, f'SeismicPlot-{self.module_name}历史记录', '暂无历史记录', QMessageBox.StandardButton.Ok)
                self.ui.close()
                return
            self.data = inclined_shaft_history_data
            for i in range(len(inclined_shaft_history_data)):
                item_data = inclined_shaft_history_data[i]
                item = QListWidgetItem(f"{i + 1} {item_data['title']} {item_data['date_time']}")
                if item_data["status"] == "success":
                    item.setIcon(QIcon(resource_path('static/image/success.png')))
                else:
                    item.setIcon(QIcon(resource_path('static/image/error.png')))
                list_widget.addItem(item)

        list_widget.setCurrentRow(0)  # 默认选中第一个的数据项

        self.init_detail(inclined_shaft_history_data[0], 1)

    # 初始化参数的具体内容，datas为历史记录文件中的inclined_shaft中的当前的数据项，index为数据项的下标
    def init_detail(self, datas, index):
        radio_item = ["是", "否"]
        is_draw = ["否", "是"]
        direction_item = ["从浅到深", "从深到浅"]

        self.ui.label_94.setText(f"{index}")
        self.ui.label.setText(f"{datas['title']}")  # 标题
        self.ui.label_2.setText(f"{datas['date_time']}")  # 日期时间
        data = datas["data"]
        # 输出文件
        self.ui.label_6.setText(f"{data['outfile']}")  # 文件名
        # 输出文件图片
        if self.image_label is not None:  # 还未设置label标签
            pixmap = load_hd_pixmap(self, data['outfile'])
            if pixmap.isNull():
                pixmap = load_hd_pixmap(self, resource_path(resource_path("static/image/no-image.png")))
            self.image_label.setPixmap(pixmap)
        else:
            self.image_label = QLabel()
            pixmap = load_hd_pixmap(self, data['outfile'])
            if pixmap.isNull():
                pixmap = load_hd_pixmap(self, resource_path(resource_path("static/image/no-image.png")))
            self.image_label.setPixmap(pixmap)
            # 保持宽高比并平滑缩放
            self.image_label.setScaledContents(True)
            self.image_label.setSizePolicy(
                QSizePolicy.Policy.Expanding,
                QSizePolicy.Policy.Expanding
            )
            layout = QVBoxLayout()
            layout.addWidget(self.image_label)
            self.ui.widget.setLayout(layout)
        # 分层文件
        self.ui.label_97.setText(f"{data['fc']}")  # 文件名
        self.ui.label_99.setText(f"{is_draw[data['fcx']]}")  # 是否画线
        # 拉平文件
        self.ui.label_8.setText(f"{data['lp']}")  # 文件名
        self.ui.label_11.setText(f"{data['trange'][0]}~{data['trange'][1]}s")  # 时间绘制范围
        self.ui.label_13.setText(f"{data['lpsd']}~{data['lped']}m")  # 深度绘制范围
        self.ui.label_15.setText(f"{radio_item[data['lpjx']]}")  # 是否做负极性
        self.ui.label_17.setText(f"{radio_item[data['lpagc']]}")  # 是否做增益
        self.ui.label_19.setText(f"{data['lpgain']}")  # 振幅大小
        self.ui.label_21.setText(f"{data['stkw']}ms")  # 走廊时窗大小
        self.ui.label_23.setText(f"{data['stkdep']}m")  # 走廊切除深度
        self.ui.label_25.setText(f"{data['timeskip']}m")  # 深度轴刻度间隔
        self.ui.label_27.setText(f"{data['skip3']}ms")  # 时间轴刻度间隔
        self.ui.label_29.setText(f"{direction_item[data['direction']]}")  # 数据深度方向
        # 走廊文件
        self.ui.label_32.setText(f"{data['stk']}")  # 文件名
        self.ui.label_34.setText(f"{radio_item[data['stkjx']]}")  # 是否做负极性
        self.ui.label_36.setText(f"{radio_item[data['stkagc']]}")  # 是否做增益
        self.ui.label_38.setText(f"{data['stkgain']}")  # 振幅大小
        # 滤波走廊文件
        self.ui.label_41.setText(f"{data['stkbf']}")  # 文件名
        self.ui.label_43.setText(f"{radio_item[data['stkbfjx']]}")  # 是否做负极性
        self.ui.label_45.setText(f"{radio_item[data['stkbfagc']]}")  # 是否做增益
        self.ui.label_47.setText(f"{data['stkbfgain']}")  # 振幅大小
        self.ui.label_49.setText(f"{data['times']}ms")  # 时移
        # 镶嵌文件
        self.ui.label_52.setText(f"{data['sei']}")  # 文件名
        self.ui.label_54.setText(f"{radio_item[data['seijx']]}")  # 是否做负极性
        self.ui.label_56.setText(f"{radio_item[data['seiagc']]}")  # 是否做增益
        self.ui.label_58.setText(f"{data['seigain']}")  # 振幅大小
        self.ui.label_60.setText(f"{data['seitimes']}ms")  # 时移
        self.ui.label_62.setText(f"{data['sein']}道")  # 绘制道数
        # 地面文件
        self.ui.label_100.setText(f"{data.get('sei_origin', '')}")  # 文件名
        # 岩性柱子
        self.ui.label_65.setText(f"{data['zhuzi']}")  # 文件名
        self.ui.label_67.setText(f"{data['zhuzidepmin']}~{data['zhuzidepmax']}m")  # 柱子深度范围
        # 其他
        self.ui.label_70.setText(f"{data['kb']}m")  # 补芯高
        self.ui.label_72.setText(f"{data['agc']}ms")  # 增益时窗
        self.ui.label_74.setText(f"{data['skip']}")  # 道间隔
        self.ui.label_76.setText(f"{data['skip2']}")  # 时间间隔
        # 设置
        self.ui.label_79.setText(f"{data['tpi']}")  # 深度比例尺
        self.ui.label_81.setText(f"{data['ips']}")  # 时间比例尺
        self.ui.label_85.setText(f"{data['colour'][0]}, {data['colour'][1]}, {data['colour'][2]}")  # rbg
        self.ui.label_87.setText(f"{data['opacity']}")  # opacity
        self.ui.label_89.setText(f"{data['lineweight']}")  # 绘制线宽
        self.ui.label_91.setText(f"{data['fontsize']}")  # fontsize
        self.ui.label_93.setText(f"{data['angle']}")  # 旋转角度

    # ========================================================
    # 初始化事件
    # ========================================================
    def init_event(self):
        self.ui.listWidget.itemClicked.connect(self.list_item_clicked)  # 列表项
        self.ui.toolButton.clicked.connect(self.load_item)  # 导入
        self.ui.toolButton_2.clicked.connect(self.del_item)  # 删除
        self.ui.toolButton_3.clicked.connect(self.del_items)  # 批量删除

    # 处理列表项被点击的事件
    def list_item_clicked(self):
        index = self.ui.listWidget.currentRow()
        self.init_detail(self.data[index], index + 1)

    # 将当前的历史记录项导入
    def load_item(self):
        index = int(self.ui.label_94.text()) - 1
        result = QMessageBox.question(None, f'SeismicPlot-{self.module_name}历史记录',
                                      f'确认导入[第{index + 1}项|{self.data[index]["title"]}]？',
                                      QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Apply | QMessageBox.StandardButton.Cancel)
        if result == QMessageBox.StandardButton.Ok:
            self.inclined_shaft.load_params(self.data[index])  # 将数据导入inclined_shaft页面
            self.ui.close()  # 关闭historyInclinedShaft页面
        elif result == QMessageBox.StandardButton.Apply:
            self.inclined_shaft.load_params(self.data[index])  # 将数据导入inclined_shaft页面
        elif result == QMessageBox.StandardButton.Cancel:
            pass

    # 将当前历史记录删除
    def del_item(self):
        index = int(self.ui.label_94.text()) - 1
        result = QMessageBox.question(None, f'SeismicPlot-{self.module_name}历史记录',
                                      f'确认删除[第{index + 1}项|{self.data[index]["title"]}]？',
                                      QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Apply | QMessageBox.StandardButton.Cancel)
        if result == QMessageBox.StandardButton.Ok:
            # 读取历史记录文件
            with open(self.path, 'r', encoding='utf-8') as file:
                history_data = json.load(file)
                inclined_shaft_history_data = history_data.get("inclinedShaft", [])
            # 删除数据
            inclined_shaft_history_data.pop(index)  # 删除self.data中的第index项
            # 关闭historyinclined_shaft页面
            self.ui.close()
            # 历史记录文件重新写入数据
            with open(self.path, 'w', encoding='utf-8') as file:
                json.dump(history_data, file, indent=4)
            # 重新加载页面内容
            self.init_content()
        elif result == QMessageBox.StandardButton.Apply:
            # 读取历史记录文件
            with open(self.path, 'r', encoding='utf-8') as file:
                history_data = json.load(file)
                inclined_shaft_history_data = history_data.get("inclinedShaft", [])
            # 删除数据
            inclined_shaft_history_data.pop(index)  # 删除self.data中的第index项
            # 历史记录文件重新写入数据
            with open(self.path, 'w', encoding='utf-8') as file:
                json.dump(history_data, file, indent=4)
            # 重新加载页面内容
            self.init_content()
        elif result == QMessageBox.StandardButton.Cancel:
            pass

    # 批量删除历史记录
    def del_items(self):
        self.ui.history_list_del_ui = HistoryListDel(self.path, self)
        self.ui.history_list_del_ui.show()
